const { v4: uuidv4 } = require("uuid");
const { query, withTransaction } = require("../utils/db");

// 分组相关业务
exports.getGroupList = async () => {
  return await query(
    "SELECT FId, FName, FIsdefault, FCreatedAt FROM t_groups ORDER BY FCreatedAt DESC"
  );
};

exports.addGroup = async (FName, FIsdefault = 0) => {
  return withTransaction(async (conn) => {
    // 如果设置为默认分组，先取消其他分组的默认状态
    if (FIsdefault) {
      await query(
        "UPDATE t_groups SET FIsdefault = 0 WHERE FIsdefault = 1",
        [],
        conn
      );
    }

    const result = await query(
      "INSERT INTO t_groups (FName, FIsdefault) VALUES (?, ?)",
      [FName, FIsdefault],
      conn
    );

    return {
      FId: result.insertId,
      FName,
      FIsdefault,
    };
  });
};

exports.updateGroup = async ({ FId, FName, FIsdefault }) => {
  return withTransaction(async (conn) => {
    // 如果设置为默认分组，先取消其他分组的默认状态
    if (FIsdefault) {
      await query(
        "UPDATE t_groups SET FIsdefault = 0 WHERE FIsdefault = 1 AND FId != ?",
        [FId],
        conn
      );
    }

    const result = await query(
      "UPDATE t_groups SET FName = ?, FIsdefault = ? WHERE FId = ?",
      [FName, FIsdefault, FId],
      conn
    );

    if (result.affectedRows === 0) {
      throw { status: 400, message: "分组不存在" };
    }

    return true;
  });
};

exports.deleteGroup = async (FId) => {
  return withTransaction(async (conn) => {
    // 1. 获取默认分组ID
    const [defaultGroup] = await query(
      "SELECT FId FROM t_groups WHERE FIsdefault = 1 LIMIT 1",
      [],
      conn
    );

    if (!defaultGroup) {
      throw { status: 400, message: "系统中没有设置默认分组" };
    }

    // 2. 检查要删除的是否是默认分组
    if (FId === defaultGroup.FId) {
      throw { status: 400, message: "不能删除默认分组" };
    }

    // 3. 把该分组下的空间转移到默认分组
    await query(
      "UPDATE t_spaces SET FGroupId = ? WHERE FGroupId = ?",
      [defaultGroup.FId, FId],
      conn
    );

    // 4. 删除分组
    const result = await query(
      "DELETE FROM t_groups WHERE FId = ?",
      [FId],
      conn
    );

    if (result.affectedRows === 0) {
      throw { status: 400, message: "分组不存在" };
    }

    return true;
  });
};

// 空间相关业务
exports.getSpaceListByGroup = async ({ FGroupId, FUserId }) => {
  let sql = `SELECT s.FId, s.FTitle, s.FDescription, s.FGroupId, s.FCreatorId, 
      u.FUsername AS FCreatorName, s.FCover, s.FTag, s.FCreatedAt,
      CASE WHEN f.FUserId IS NOT NULL THEN TRUE ELSE FALSE END AS FIsStarred
    FROM t_spaces s
    LEFT JOIN t_users u ON s.FCreatorId = u.FUserId
    LEFT JOIN t_user_space_favorites f ON s.FId = f.FSpaceId AND f.FUserId = ?
  `;

  const params = [FUserId || ""]; // FUserId 可能为空，写 "" 不匹配

  if (FGroupId) {
    sql += " WHERE s.FGroupId = ?";
    params.push(FGroupId);
  }

  sql += " ORDER BY s.FCreatedAt DESC";

  return await query(sql, params);
};

exports.searchSpace = async ({ FKeyword, FUserId }) => {
  const likeStr = `%${FKeyword}%`;
  const sql = `SELECT s.FId, s.FTitle, s.FDescription, s.FGroupId, s.FCreatorId, 
      u.FUsername AS FCreatorName, s.FCover, s.FTag, s.FCreatedAt,
      CASE WHEN f.FUserId IS NOT NULL THEN TRUE ELSE FALSE END AS FIsStarred
    FROM t_spaces s
    LEFT JOIN t_users u ON s.FCreatorId = u.FUserId
    LEFT JOIN t_user_space_favorites f ON s.FId = f.FSpaceId AND f.FUserId = ?
    WHERE s.FTitle LIKE ? OR s.FDescription LIKE ? OR s.FTag LIKE ?
    ORDER BY s.FCreatedAt DESC`;

  return await query(sql, [FUserId || "", likeStr, likeStr, likeStr]);
};

exports.createSpace = async ({
  FTitle,
  FDescription,
  FGroupId,
  FTag,
  FCover,
  FCreatorId,
}) => {
  const FId = uuidv4();

  await query(
    `INSERT INTO t_spaces (FId, FTitle, FDescription, FGroupId, FCreatorId, FTag, FCover) 
     VALUES (?, ?, ?, ?, ?, ?, ?)`,
    [FId, FTitle, FDescription, FGroupId, FCreatorId, FTag || "", FCover || ""]
  );

  return { FId, FTitle, FGroupId, FCreatorId };
};

exports.toggleFavorite = async ({ FSpaceId, FUserId, FIsStarred }) => {
  if (FIsStarred) {
    // 取消收藏前先查是否存在，避免重复插入
    const exists = await query(
      "SELECT * FROM t_user_space_favorites WHERE FUserId = ? AND FSpaceId = ?",
      [FUserId, FSpaceId]
    );

    if (exists.length === 0) {
      await query(
        "INSERT INTO t_user_space_favorites (FUserId, FSpaceId) VALUES (?, ?)",
        [FUserId, FSpaceId]
      );
    }
  } else {
    await query(
      "DELETE FROM t_user_space_favorites WHERE FUserId = ? AND FSpaceId = ?",
      [FUserId, FSpaceId]
    );
  }

  return { FIsStarred };
};

// 更新空间信息
exports.updateSpace = async ({
  FId,
  FTitle,
  FDescription,
  FGroupId,
  FTag,
  FCover,
  FModifierId,
}) => {
  const updates = [];
  const params = [];

  if (FTitle !== undefined) {
    updates.push("FTitle = ?");
    params.push(FTitle);
  }

  if (FDescription !== undefined) {
    updates.push("FDescription = ?");
    params.push(FDescription);
  }

  if (FGroupId !== undefined) {
    updates.push("FGroupId = ?");
    params.push(FGroupId);
  }

  if (FTag !== undefined) {
    updates.push("FTag = ?");
    params.push(FTag || ""); // 允许清空标签
  }

  if (FCover !== undefined) {
    updates.push("FCover = ?");
    params.push(FCover || ""); // 允许清空封面
  }
  if (FModifierId !== undefined) {
    updates.push("FModifierId = ?");
    params.push(FModifierId || ""); // 允许清空封面
  }
  if (updates.length === 0) {
    throw { status: 400, message: "无更新内容" };
  }

  params.push(FId);
  const sql = `UPDATE t_spaces SET ${updates.join(", ")} WHERE FId = ?`;
  const result = await query(sql, params);

  if (result.affectedRows === 0) {
    throw { status: 400, message: "空间不存在" };
  }

  return true;
};

// 删除空间及其相关内容（使用事务处理）
exports.deleteSpace = async (FId) => {
  return withTransaction(async (conn) => {
    // 1. 删除空间下的所有文档节点（如果外键没有设置级联删除）
    await query("DELETE FROM t_doc_nodes WHERE FSpaceId = ?", [FId], conn);

    // 2. 删除空间相关的收藏记录
    await query(
      "DELETE FROM t_user_space_favorites WHERE FSpaceId = ?",
      [FId],
      conn
    );

    // 3. 删除空间本身
    const result = await query(
      "DELETE FROM t_spaces WHERE FId = ?",
      [FId],
      conn
    );

    if (result.affectedRows === 0) {
      throw { status: 400, message: "空间不存在" };
    }

    return true;
  });
};

exports.getSpaceDetail = async (FId) => {
  const sql = `SELECT s.*, g.FName AS FGroupName, u.FUsername AS FCreatorName
    FROM t_spaces s
    LEFT JOIN t_groups g ON s.FGroupId = g.FId
    LEFT JOIN t_users u ON s.FCreatorId = u.FUserId
    WHERE s.FId = ?`;

  const rows = await query(sql, [FId]);

  if (rows.length === 0) {
    throw { status: 400, message: "空间不存在" };
  }

  return rows[0];
};

// 在 space.js 中添加以下方法

// 添加空间管理员
exports.addSpaceAdmin = async (FSpaceId, FUserId) => {
  return withTransaction(async (conn) => {
    // 检查空间是否存在
    const [space] = await query(
      "SELECT 1 FROM t_spaces WHERE FId = ?",
      [FSpaceId],
      conn
    );
    if (!space) {
      throw { status: 400, message: "空间不存在" };
    }

    // 检查用户是否存在
    const [user] = await query(
      "SELECT 1 FROM t_users WHERE FUserId = ?",
      [FUserId],
      conn
    );
    if (!user) {
      throw { status: 400, message: "用户不存在" };
    }

    // 检查是否已经是管理员
    const [existing] = await query(
      "SELECT 1 FROM t_space_admins WHERE FSpaceId = ? AND FUserId = ?",
      [FSpaceId, FUserId],
      conn
    );
    if (existing) {
      throw { status: 400, message: "该用户已经是空间管理员" };
    }

    // 添加管理员
    await query(
      "INSERT INTO t_space_admins (FSpaceId, FUserId) VALUES (?, ?)",
      [FSpaceId, FUserId],
      conn
    );

    return true;
  });
};

// 移除空间管理员
exports.removeSpaceAdmin = async (FSpaceId, FUserId) => {
  return withTransaction(async (conn) => {
    const result = await query(
      "DELETE FROM t_space_admins WHERE FSpaceId = ? AND FUserId = ?",
      [FSpaceId, FUserId],
      conn
    );

    if (result.affectedRows === 0) {
      throw { status: 400, message: "该用户不是空间管理员或记录不存在" };
    }

    return true;
  });
};

// 获取空间管理员列表
exports.getSpaceAdmins = async (FSpaceId) => {
  const sql = `SELECT u.FUserId, u.FUsername, u.FEmail, sa.FCreatedAt 
               FROM t_space_admins sa
               JOIN t_users u ON sa.FUserId = u.FUserId
               WHERE sa.FSpaceId = ?
               ORDER BY sa.FCreatedAt DESC`;
  
  return await query(sql, [FSpaceId]);
};

// 检查用户是否是空间管理员
exports.isSpaceAdmin = async (FUserId, FSpaceId) => {
  // 首先检查是否是超级管理员(拥有space:manage权限)
  const [hasPermission] = await query(
    `SELECT 1 FROM t_user_roles ur
     JOIN t_role_permissions rp ON ur.FRoleId = rp.FRoleId
     JOIN t_permissions p ON rp.FPermissionId = p.FId
     WHERE ur.FUserId = ? AND p.FCode = 'space:manage'`,
    [FUserId]
  );

  if (hasPermission) {
    return true;
  }

  // 如果不是超级管理员，检查是否是空间管理员
  const [isAdmin] = await query(
    "SELECT 1 FROM t_space_admins WHERE FUserId = ? AND FSpaceId = ?",
    [FUserId, FSpaceId]
  );

  return !!isAdmin;
};
